import { useEffect, useRef } from 'react';
import events from '@/utils/eventBus';
import EVENTBUS_TYPES from '@/pages/Recruitment/Interview/utils/EVENTBUS_TYPES';

/**
 * 获取网络状态Ref，下线以浏览器 offline 事件为准，上线以socket重连为准
 */
const useNetWorkState = () => {
    const onlineStateRef = useRef(true); // 浏览器在线状态
    const handleDisconnect = () => {
        onlineStateRef.current = false;
    };
    const handleConnected = () => {
        onlineStateRef.current = true;
    };
    useEffect(() => {
        window.addEventListener('offline', handleDisconnect); // 监听浏览器断网
        window.addEventListener('online', handleConnected); // 监听浏览器断网
        events.addListener(EVENTBUS_TYPES.SOCKET_CONNECTED, handleConnected); // 网络接通以socket连接成功为准
        return () => {
            window.removeEventListener('offline', handleDisconnect);
            window.removeEventListener('online', handleConnected);
            events.removeListener(EVENTBUS_TYPES.SOCKET_CONNECTED, handleConnected);
        };
    }, []);

    return onlineStateRef;
};

export default useNetWorkState;
